package com.yungu.swift.api.base.gateway;

import com.yungu.swift.api.route.v2.passenger.PasLoginApi;
import com.yungu.swift.api.utils.JwtHelper;
import com.yungu.swift.autoconfig.redis.RedisStringCacheService;
import com.yungu.swift.base.SpringContextHolder;
import com.yungu.swift.base.model.api.ApiParam;
import com.yungu.swift.constants.CommonConstant;
import com.yungu.swift.utils.JsonUtils;
import com.yungu.swift.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import java.io.IOException;
import java.util.Objects;

/**
 * @author : cuixiuyin
 * @date : 2019/7/9
 */
@Slf4j
public class CurrentUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

    /**
     * 用于判定是否需要处理该参数分解，返回 true 为需要，并会去调用下面的方法resolveArgument。
     *
     * @param methodParameter
     * @return
     */
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return ApiParam.class.isAssignableFrom(methodParameter.getParameterType())
                && methodParameter.hasParameterAnnotation(CurrentUser.class);
    }

    /**
     * 真正用于处理参数分解的方法，返回的 Object 就是controller方法上的形参对象。
     *
     * @param methodParameter
     * @param modelAndViewContainer
     * @param nativeWebRequest
     * @param webDataBinderFactory
     * @return
     * @throws Exception
     */
    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        String accessToken = nativeWebRequest.getHeader(GatewayHeader.accessToken);
        if (StringUtils.isEmpty(accessToken)) {
            return null;
        }
        String rid = nativeWebRequest.getHeader(GatewayHeader.rid);
        String prefix = Objects.equals(rid, CommonConstant.PASSENGER + "") ? PasLoginApi.ACCESS_TOKEN_PREFFIX : "DRIVER_ACCESS_TOKEN_";
        try {
            RedisStringCacheService stringCacheService = SpringContextHolder.getBean(RedisStringCacheService.class);
            String jsonApiParam = stringCacheService.get(prefix + accessToken);
            if (StringUtils.isEmpty(jsonApiParam)) {
                throw new Exception();
            }
            return JsonUtils.readValue(jsonApiParam, ApiParam.class);
        } catch (Exception e) {
            log.warn("CurrentUserHandlerMethodArgumentResolver redis get apiParam error. accessToken:{}", accessToken);
            // 异常的时候做 jwt 降级方案
            String jwts = nativeWebRequest.getHeader(GatewayHeader.jwts);
            String parseJWT = JwtHelper.parseJWT(jwts);
            try {
                return JsonUtils.readValue(parseJWT, ApiParam.class);
            } catch (IOException ex) {
                log.error("CurrentUserHandlerMethodArgumentResolver resolveArgument readValue error. parseJWT:{}", parseJWT, e);
            }
        }
        return null;
    }
}
